import { DEFAULT_LOCATION } from '@/env'
import { tGetMapKey, tLoadMapScript, tGetDistrict, tGeolocation, tAddressToLocation, tNearbyAddress, tSearchAddress,tLocationsToGcj02 } from "./tencentApi"
import { gGetMapKey, gLoadMapScript, gGetDistrict, gGeolocation, gAddressToLocation, gNearbyAddress, gSearchAddress } from "./googleApi"
import { toastApp } from '@/common/utils/toast'
import { empty,sleep } from '@/common/utils'
// #ifdef APP-PLUS
import { checkLocationPermission } from '@/common/utils/permission/check'
// #endif
import { getMapKey as getMapKey1 } from '@/common/request/api'

// #ifdef SUBSCRIPTION ||  PRIVATE
import { wxGetLocation } from '@/common/wxInit'
// #endif


let appMapType = 'tencent'
const defaultLatitude = DEFAULT_LOCATION[0]
const defaultLongitude = DEFAULT_LOCATION[1]

const getMapKey = async () => {
	const api = appMapType === 'tencent' ? tGetMapKey : gGetMapKey
	const res = api()
	return res
}
// 腾讯地图省市区列表
const getDistrict = async () => {
	const api = appMapType === 'tencent' ? tGetDistrict : gGetDistrict
	const res = await api()
	return res
}

// 地图初始化
const loadMapScript = (...args: Parameters<typeof tLoadMapScript>) => {
	return appMapType === 'tencent' ? tLoadMapScript(...args) : gLoadMapScript(...args)
}
// 根据ip获取定位
// const getIPLocation = appMapType === 'tencent' ? tGetIPLocation : gGetIPLocation
// 根据地址信息转换经纬度
const addressToLocation = async (...args: Parameters<typeof tAddressToLocation>) => {
	const api = appMapType === 'tencent' ? tAddressToLocation : gAddressToLocation
	const res = await api(...args)
	return res
}
// 逆地址解析
const geolocation = async (...args: Parameters<typeof tGeolocation>) => {
	const api = appMapType === 'tencent' ? tGeolocation : gGeolocation
	const res = await api(...args)
	return res
}

// 附近地点
const nearbyAddress = async (...args: Parameters<typeof tNearbyAddress>) => {
	const api = appMapType === 'tencent' ? tNearbyAddress : gNearbyAddress
	const res = await api(...args)
	return res
}
// 搜索地点
const searchAddress = async (...args: Parameters<typeof tSearchAddress>) => {
	const api = appMapType === 'tencent' ? tSearchAddress : gSearchAddress
	const res = await api(...args)
	return res
}

const mapInit = async () => {
	const res = await getMapKey1()
	if (res.code == 200 && res.data?.keyType) {
		appMapType = res.data.keyType === '1' ? 'tencent' : 'google'
	}
	// if(process.env.NODE_ENV === 'development'){
	// 	res.data.key = ['YENBZ-UWUCQ-VIJ5V-G6DCI-7BDO5-RPFBJ']
	// }
	loadMapScript(res.data.key)
	return res
}


const getLocation = (errText1: string, errText2: string, isGeolocation = true):Promise<{
	latitude:number
	longitude:number
	address_component:{
		city:string
	}
}> => {
	return new Promise((resolve, reject) => {
		// #ifdef SUBSCRIPTION ||  PRIVATE
		wxGetLocation().then(res => {
			let { latitude, longitude } = res
			geolocation(latitude, longitude, isGeolocation)
				.then(resolve)
				.catch(reject)
		})
		// #endif
		// #ifdef MP || HTML5 || PREVIEW
		uni.getLocation({
			// #ifdef MP
			type: "gcj02",
			// #endif
			success: async (res: { latitude: number; longitude: number }) => {
				let { latitude, longitude } = res;
				// #ifndef MP
				if(appMapType === 'tencent'){
					const _res = await tLocationsToGcj02({
						latitude,
						longitude
					})
					latitude = _res.latitude
					longitude = _res.longitude
				}
				
				
				// #endif
				geolocation(latitude, longitude, isGeolocation).then(resolve).catch(reject);
			},
			fail: async (e) => {
				console.log("获取当前位置失败");
				// 使用默认的坐标
				geolocation(defaultLatitude, defaultLongitude, isGeolocation)
					.then(resolve)
					.catch(reject);
			},
		});
		// #endif
		// #ifdef APP
		checkLocationPermission().then(() => {
			plus.geolocation.getCurrentPosition(
				async (res) => {
					console.log("当前位置的wgs84经度：" + res.coords?.longitude);
					console.log("当前位置的wgs84纬度：" + res.coords?.latitude);
					if(res.coords&&!empty(res.coords.latitude)&&!empty(res.coords.longitude)){
						const _res = await tLocationsToGcj02({
							latitude:res.coords.latitude!,
							longitude:res.coords.longitude!
						})
						const latitude = _res.latitude
						const longitude = _res.longitude
						geolocation(latitude, longitude, isGeolocation)
							.then(resolve)
							.catch(reject);
					}else{
						reject()
					}
					
				},
				(err) => {
					if (err.code === 1 || err.code === 2) {
						toastApp(errText1)
					} else {
						toastApp(errText2)
					}
					geolocation(defaultLatitude, defaultLongitude, isGeolocation)
						.then(resolve)
						.catch(reject);
				},
				{
					timeout: 10000,
					provider: "system",
					geocode: false,
				}
			);
		})

		// #endif
	});
};


export { mapInit, getMapKey, loadMapScript, getLocation, geolocation, getDistrict, defaultLatitude, defaultLongitude, addressToLocation, nearbyAddress, searchAddress }
